package com.huahan.auth.Utils;

import cn.hutool.json.JSONUtil;
import com.huahan.auth.api.OAuth2Api;
import com.huahan.auth.exception.BusinessException;
import com.mall.common.constant.CacheNameConstant;
import com.mall.common.constant.ResultCode;
import com.mall.common.constant.SecurityConstant;
import com.mall.common.utils.StringStrUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 1. @Description
 * 2. @Author wj
 * 3. @Date 2024/4/26 15:57
 * 4. @Version 1.0
 */
@Component
public class CommonLoginUtils {
    private static final Logger logger = LoggerFactory.getLogger(CommonLoginUtils.class);

    @Value("${OAuth2.client_id}")
    private String client_id;
    @Value("${OAuth2.client_secret}")
    private String client_secret;
    @Autowired
    private OAuth2Api auth2Api;
    @Resource
    private RedisHelper redisHelper;

    public Map<String, Object> login(Map<String, String> params){
        try {
            params.put("client_id", client_id);
            params.put("client_secret", client_secret);
            String jsonString = auth2Api.oauthToken(params);
            Map<String, Object> authInfo = MapperUtils.json2map(jsonString);
            String accessToken = (String) authInfo.get(OAuth2AccessToken.ACCESS_TOKEN);
            if (StringUtils.isEmpty(accessToken)) {
                Integer code = (Integer) authInfo.get("code");
                String message = (String) authInfo.get("message");
                throw new BusinessException(message, code);
            }
            String refreshToken = (String) authInfo.get(OAuth2AccessToken.REFRESH_TOKEN);
            redisHelper.cacheValue(
                    String.format(CacheNameConstant.REFRESH_TOKEN_KEY, refreshToken),
                    refreshToken,
                    SecurityConstant.REFRESH_TOKEN_VALIDITY,
                    TimeUnit.SECONDS
            );
            if(StringStrUtils.isNotBlank(params.get("phone"))){
                redisHelper.cacheValue(String.format(CacheNameConstant.FIND_USER_INFO_KEY,params.get("phone")), JSONUtil.toJsonStr(authInfo), SecurityConstant.REFRESH_TOKEN_VALIDITY, TimeUnit.SECONDS);
            }else if(StringStrUtils.isNotBlank(params.get("username"))){
                redisHelper.cacheValue(String.format(CacheNameConstant.FIND_USER_INFO_KEY,params.get("username")), JSONUtil.toJsonStr(authInfo), SecurityConstant.REFRESH_TOKEN_VALIDITY, TimeUnit.SECONDS);
            }
            return authInfo;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("调用 /oauth/token get token 失败; {}", e.getMessage());
            Integer code = ResultCode.AUTH_SERVER_ERROR.getCode();
            String message = ResultCode.AUTH_SERVER_ERROR.getMessage();
            if (e instanceof BusinessException) {
                BusinessException be = (BusinessException) e;
                code = be.getCode();
                message = be.getMessage();
            }
            throw new BusinessException(message, code);
        }
    }

}
